<template>
    <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'

// 在 setup 作用域中定义 chartRef
const chartRef = ref()

//数据调用
const props = defineProps({
  data: { type: Array, default: [] },
  legendName: { type: String, default: "内容数量" }
})

let myChart = null;
const resizeChart = () => {
  if (myChart) {
    myChart.resize()
  }
}
const initChart = () => {

  if (!chartRef.value) return;

  // 如果已有实例则先销毁
  if (myChart) {
    myChart.dispose();
  }
  myChart = echarts.init(chartRef.value)
  var option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: props.legendName,
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 10
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: props.data
      }
    ]
  };
  option && myChart.setOption(option);
}

watch(() => props.data, () => {
  initChart();
})

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  myChart.dispose()
})
</script>